package com.yamaha.bikemarket;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.facebook.Session;
import com.loopj.android.http.AsyncHttpClient;
import com.testflightapp.lib.TestFlight;
import com.yamaha.bikemarket.api.API;
import com.yamaha.bikemarket.util.LogUtil;
import com.yamaha.bikemarket.util.SCStaticFunc;
import com.yamaha.bikemarket.util.Utils;

public class SplashFragment extends Activity {

	private final AsyncHttpClient client = new AsyncHttpClient();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);

		TestFlight.takeOff(getApplication(),
				"af5aad01-24b4-43e1-84dc-e461c7a5d97b");

		if (!Utils.isNetworkConnected(this)) {
			Utils.showAlertDialog(this, "Error",
					getResources().getString(R.string.no_network_connection));
			return;
		}

		Session session = Session.getActiveSession();
		if (session != null) {
			session.closeAndClearTokenInformation();
			TestFlight.log("Clear Facebook Session in SplashScreen.");
			Log.d("Facebook", "Clear Session.");
		}

		final Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				handleGetInitData();

			}
		}, 1500);
	}

	private void handleGetInitData() {
		client.post(API.GET_INIT_DATA, new MyAsyncHttpResponseHandler(
				API.GET_INIT_DATA, this) {

			@Override
			public void onSuccess(String res) {
				super.onSuccess(res);

				try {
					final JSONObject obj = new JSONObject(res);
					final JSONObject msgObj = obj.getJSONObject("message");

					final JSONArray brand = msgObj.getJSONArray("brand");
					final JSONArray color = msgObj.getJSONArray("color");
					final JSONArray province = msgObj.getJSONArray("province");

					SCStaticFunc.setData(SplashFragment.this,
							SCStaticFunc.BAND, brand);
					SCStaticFunc.setData(SplashFragment.this,
							SCStaticFunc.COLOR, color);
					SCStaticFunc.setData(SplashFragment.this,
							SCStaticFunc.PROVINCE, province);

					changeToLoginActivity();
				} catch (JSONException e) {
					LogUtil.e("Get Init Data", e.getMessage(), e);
				}
			}
		});
	}

	private void changeToLoginActivity() {
		finish();
		overridePendingTransition(0, 0);
		final Intent intent = new Intent(SplashFragment.this,
				LoginFragment.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		startActivity(intent);

	}

}
